package com.yt.base.controller.app;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yt.app.core.interfaces.AppTopicCategoryService;
import com.yt.app.core.interfaces.AppTopicService;
import com.yt.app.core.model.AppTopic;
import com.yt.app.core.model.AppTopicCategory;
import com.yt.base.controller.core.BaseController;
import com.yt.base.vo.AppTopicVo;
import com.yt.core.MsgBean;
import com.yt.core.dao.PagingBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.util.YitianConfig;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/app/topic/")
public class AppTopicController extends BaseController {

    @Autowired
    private AppTopicService appTopicService;

    @Autowired
    private AppTopicCategoryService appTopicCategoryService;

    @RequestMapping("list")
    public ModelAndView list(@RequestParam(value = "start", required = false) String start,
                             @RequestParam(value = "limit", required = false) String limit) {
        ModelAndView mav = new ModelAndView("/app/topic/list");
        try {
            QueryFilter filter = new DynamicSQLFilterImpl();
            filter.setSortField("id", true);
            PagingBean page = new PagingBean();
            int currentPage = 0;
            int pageSize = 25;
            if (StringUtils.isNotEmpty(limit) && StringUtils.isNumeric(limit)) {
                pageSize = Integer.parseInt(limit);
            }
            if (StringUtils.isNotEmpty(start) && StringUtils.isNumeric(start)) {
                currentPage = (Integer.parseInt(start) - 1) * pageSize;
            }
            page.setPageSize(pageSize);
            page.setStart(currentPage);

            List<AppTopic> list = appTopicService.find(filter);

            Map<Long, String> topicCategoryMap = getTopicCategoryMapByIds(list);

            List<AppTopicVo> voList = Lists.newArrayList();
            for (AppTopic appTopic : list) {
                AppTopicVo vo = new AppTopicVo();
                BeanUtils.copyProperties(vo, appTopic);
                String name=topicCategoryMap.get(appTopic.getCategoryId());
                vo.setCategoryName(Strings.isNullOrEmpty(name)?"":name);
                voList.add(vo);
            }

            int total = appTopicService.count(filter);
            mav.addObject("total", total);
            mav.addObject("list", voList);
        }catch (Exception ex){

        }
        return mav;
    }

    private Map<Long,String> getTopicCategoryMapByIds(List<AppTopic> list){
        List<Long> categoryIdList= Lists.newArrayList();
        for(AppTopic appTopic:list){
            if(appTopic.getCategoryId()!=null && appTopic.getCategoryId()>0) {
                categoryIdList.add(appTopic.getCategoryId());
            }
        }
        Map<Long,String> categoryMap= Maps.newHashMap();
        if(categoryIdList.size()==0){
            return categoryMap;
        }
        QueryFilter filter=new DynamicSQLFilterImpl();
        filter.addFilter("Q_id_S_IN", Joiner.on(",").join(categoryIdList));
        filter.setPagingBean(new PagingBean(0,1000));
        List<AppTopicCategory> categoryList=appTopicCategoryService.find(filter);
        if(categoryList!=null && categoryList.size()>0){
            for(AppTopicCategory appTopicCategory:categoryList){
                categoryMap.put(appTopicCategory.getId(),appTopicCategory.getName());
            }
        }
        return categoryMap;
    }



    @RequestMapping("toAdd")
    public ModelAndView toAdd() {
        ModelAndView mav = new ModelAndView("/app/topic/add");
        QueryFilter filter = new DynamicSQLFilterImpl();
        filter.setPagingBean(new PagingBean(0, 100000));
        filter.setSortField("id", false);
        mav.addObject("topicCategoryList", appTopicCategoryService.find(filter));
        return mav;
    }


    @RequestMapping("toEdit")
    public ModelAndView toEdit(@RequestParam(value = "id", required = true) Long id) {
        ModelAndView mav = new ModelAndView("/app/topic/add");
        AppTopic appTopic = appTopicService.get(id);
        QueryFilter filter = new DynamicSQLFilterImpl();
        filter.setPagingBean(new PagingBean(0, 100000));
        filter.setSortField("id", false);
        mav.addObject("topicCategoryList", appTopicCategoryService.find(filter));
        mav.addObject("bean", appTopic);
        return mav;
    }

    @RequestMapping("save")
    public
    @ResponseBody
    Object save(@RequestParam(value = "id", required = false) Long id,
                @RequestParam(value = "categoryId", required = false) Long categoryId,
                @RequestParam(value = "title", required = false) String title,
                @RequestParam(value = "image", required = false) String image,
                @RequestParam(value = "content", required = false) String content) {
        MsgBean msg = new MsgBean();
        try {
            AppTopic appTopic = null;
            if (id != null && id > 0) {
                appTopic = appTopicService.get(id);
            }
            if (appTopic == null) {
                appTopic = new AppTopic();
                appTopic.setFavNum(0);
                appTopic.setViewNum(0);
                appTopic.setDateline(System.currentTimeMillis() / 1000);
            }
            appTopic.setCategoryId(categoryId);
            if (Strings.isNullOrEmpty(title)) {
                msg.setFailure(1, "标题不能为空！");
                return msg.returnMsg();
            } else if (title.length() > 20) {
                msg.setFailure(1, "标题不能超过20个字符！");
                return msg.returnMsg();
            }
            appTopic.setTitle(title.trim());

            //imgage
            {
                if (Strings.isNullOrEmpty(image)) {
                    msg.setFailure(1, "请上传图片！");
                    return msg.returnMsg();
                }
                List<String> imageList = Splitter.on(",").splitToList(image);
                if (imageList == null || imageList.size() == 0) {
                    msg.setFailure(1, "请上传图片！");
                    return msg.returnMsg();
                }
                image = imageList.get(0);
                if (image.startsWith(YitianConfig.IMAGE_ACCESS_URL)) {
                    appTopic.setImage(image);
                } else {
                    appTopic.setImage(YitianConfig.IMAGE_ACCESS_URL + "/" + image);
                }
            }
            if (Strings.isNullOrEmpty(content)) {
                msg.setFailure(1, "内容不能为空！");
                return msg.returnMsg();
            }
            appTopic.setContent(content);

            if (appTopic.getId() != null && appTopic.getId() > 0) {
                appTopicService.update(appTopic);
            } else {
                appTopicService.insert(appTopic);
            }
        }catch (Exception e){
            msg.setFailure(1,"操作失败，请检查参数是否正确！");
        }
        return msg.returnMsg();
    }

    @RequestMapping("/multiDel")
    @ResponseBody
    public Object multiDel(@RequestParam("ids") String ids) {
        MsgBean msg = new MsgBean();
        String[] idArr = ids.split(",");
        if (ids != null) {
            for (String id : idArr) {
                appTopicService.remove(Long.valueOf(id));
            }
        }
        return msg.returnMsg();
    }


}
